﻿using System;
using System.IO.Pipes;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using DxfViewer;
using Newtonsoft.Json;

namespace SDBConverter
{
    internal class Program
    {
        internal class InitArgs {
            /// <summary>
            /// 划线层颜色（默认绿色）
            /// </summary>
            public string LineLayerColor { get; set; } = "#00FF00";

            /// <summary>
            /// 印字层颜色（默认橙色）
            /// </summary>
            public string TextLayerColor { get; set; } = "#FFA500";

            /// <summary>
            /// 信息层颜色（默认蓝色）
            /// </summary>
            public string InfoLayerColor { get; set; } = "#0000FF";

            public string SrcFilePath { get; set; } = string.Empty;

            public override string ToString() {
                return $"转换文件:{this.SrcFilePath}\nLineLayerColor:{LineLayerColor}\tTextLayerColor:{TextLayerColor}\tInfoLayerColor:{InfoLayerColor}";
            }
            [JsonIgnore]
            public int LineLayerColorValue { get { return this.TestColorConversion(LineLayerColor); } }
            [JsonIgnore]
            public int TextLayerColorValue { get { return this.TestColorConversion(TextLayerColor); } }
            [JsonIgnore]
            public int DashLayerColorValue { get { return this.TestColorConversion(InfoLayerColor); } }

            private int TestColorConversion(string hexColor) {
                try {

                    if (string.IsNullOrEmpty(hexColor.Trim())) {
                        return -1;
                    }

                    // Handle both RGB (#RRGGBB) and ARGB (#AARRGGBB) formats
                    if (hexColor.StartsWith("#")) {
                        string hexDigits = hexColor.Substring(1);

                        if (hexDigits.Length == 6) {// RGB format
                            int colorValue = Convert.ToInt32(hexDigits, 16);
                            Console.WriteLine($"RGB value: {colorValue} (0x{colorValue:X6})");
                            return colorValue;
                        } else if (hexDigits.Length == 8) {// ARGB format
                            int colorValue = (int)(uint.Parse(hexDigits, System.Globalization.NumberStyles.HexNumber));
                            Console.WriteLine($"ARGB value: {colorValue} (0x{colorValue:X8})");
                            return colorValue;
                        } else {
                            Console.WriteLine($"Invalid color string length. Expected 6 or 8 hex digits after #, got {hexDigits.Length}");
                        }
                    } else {
                        Console.WriteLine("Color string must start with #");
                    }
                } catch (Exception ex) {
                    Console.WriteLine($"Error: {ex.Message}");
                } finally {
                    Console.WriteLine(new string('-', 40));
                }

                return -1;
            }
        }

        [DllImport("libs/TAM.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern int CheckRuntime();

       
        static void Main(string[] args)
        {
            // 检查运行环境
            int result = CheckRuntime();
            if (result != 0)
            {
                return;
            }

            if (args.Length == 0)
            {
                Console.WriteLine("缺少管道名称参数");
                return;
            }

            string pipeName = args[0];

            using (NamedPipeServerStream pipeServer = new NamedPipeServerStream(pipeName, PipeDirection.InOut))
            {
                Console.WriteLine("等待主程序连接...");
                pipeServer.WaitForConnection();

                // 接收文件路径
                byte[] buffer = new byte[1024];
                int bytesRead = pipeServer.Read(buffer, 0, buffer.Length);
                string initArgJson = Encoding.UTF8.GetString(buffer, 0, bytesRead).Trim();
                InitArgs initArgs =JsonConvert.DeserializeObject<InitArgs>(initArgJson);                
                Console.WriteLine(initArgs);

                SDB2DxfProcessor sDB2DxfProcessor = new SDB2DxfProcessor(initArgs.LineLayerColorValue, initArgs.DashLayerColorValue, initArgs.TextLayerColorValue);
                // 执行数据转换逻辑
                var dxfFile = sDB2DxfProcessor.ProcessFile(initArgs.SrcFilePath);

                // 获取当前程序所在目录
                string currentDirectory = AppDomain.CurrentDomain.BaseDirectory.TrimEnd('\\'); 

                // 获取当前程序所在目录的上一层目录
                string parentDirectory = Directory.GetParent(currentDirectory).FullName;

                // 构造临时目录路径
                string tempDirectory = Path.Combine(parentDirectory, "SDBConverterTemp");

                if (!Directory.Exists(tempDirectory))
                {
                    Directory.CreateDirectory(tempDirectory);
                }

                // 生成 DXF 文件路径
                string dxfFileName = Path.GetFileNameWithoutExtension(initArgs.SrcFilePath) + ".dxf";
                string dxfFilePath = Path.Combine(tempDirectory, dxfFileName);

                if(File.Exists(dxfFilePath))
                {
                    File.Delete(dxfFilePath);
                }
                    
                // 保存 DXF 文件
                dxfFile.Save(dxfFilePath);

                Console.WriteLine("DXF 文件已保存到: " + dxfFilePath);
            }
        }
    }
}
